<template>
  <a-form-item
    :label="labelName"
    :labelCol="labelCol"
    :wrapperCol="wrapperCol"
    has-feedback=""
  >
    <a-upload
      :customRequest="req"
      :disabled="isDisabled"
      :remove="del"
      :file-list="fileList"
      v-decorator="[colName, {rules: rules}]">
      <a-button v-if="!isDisabled">
        <a-icon type="upload" /> 点击上传
      </a-button>
    </a-upload>
  </a-form-item>
</template>

<script>
import { sysFileInfoDelete, sysFileInfoDetail, sysFileInfoUpload } from '@/api/modular/system/fileManage'
// import { downloadById } from '@/api/modular/main/crmcontract/crmPayContractManage'
const downloadById = '/api/sysFileInfo/download?id='

export default {
  name: 'CustomUpload',
  props: {
    labelCol: {
      type: Object,
      default: null,
      required: true
    },
    wrapperCol: {
      type: Object,
      default: null,
      required: true
    },
    labelName: {
      type: String,
      default: null,
      required: true
    },
    colName: {
      type: String,
      default: null,
      required: true
    },
    rules: {
      type: Array,
      default: null,
      required: false
    },
    isDisabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    return {
      fileList: []
    }
  },
  methods: {
    // 上传文件
    req (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      sysFileInfoUpload(formData).then((res) => {
        if (res.success) {
          const file = {
            uid: res.data,
            name: data.file.name,
            url: downloadById + res.data
          }
          this.fileList.push(file)
          this.$message.success('上传成功')
        } else {
          this.$message.error('上传失败：' + res.message)
        }
      })
    },
    // 删除文件
    del (data) {
      sysFileInfoDelete({ id: data.uid }).then((res) => {
        if (res.success) {
          this.fileList.splice(this.fileList.indexOf(data), 1)
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    setFileList (data) {
      // 附件数据
      const temp = []
      if (data !== undefined && data !== null && data !== '') {
        data.split(';').forEach(item => {
          sysFileInfoDetail({ id: item }).then(res => {
            const file = {
              uid: res.data.id,
              name: res.data.fileOriginName,
              url: downloadById + res.data.id
            }
            temp.push(file)
          })
        })
      }
      this.fileList = temp
    },
    getFileList () {
      let temp = ''
      this.fileList.forEach((item, index) => {
        temp += item.uid
        if (this.fileList.length !== index + 1) {
          temp += ';'
        }
      })
      return temp
    }
  }
}
</script>

<style scoped>

</style>
